//
//  WebTableViewCell.m
//  Buzz API Demo
//
//  Created by Peter Hopkins on 5/11/10.
//  Copyright 2010 Google Inc. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "WebTableViewCell.h"


@implementation WebTableViewCell

@synthesize userData = userData_;
@synthesize delegate = delegate_;
@dynamic HTML;
@dynamic height;


- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier {
  if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]) {
    CGRect webViewFrame = CGRectMake(10, 0, 280, 1);
    webView_ = [[UIWebView alloc] initWithFrame:webViewFrame];
    [webView_ setDelegate:self];
    [webView_ setOpaque:NO];
    [webView_ setBackgroundColor:[UIColor clearColor]];

    [self setClipsToBounds:YES];
    [self addSubview:webView_];
  }

  return self;
}


- (NSString *)HTML {
  return HTML_;
}


- (void)setHTML:(NSString *)HTML {
  [HTML_ autorelease];
  HTML_ = [HTML retain];

  loaded_ = NO;
  [webView_ setHidden:YES];
  [webView_ loadHTMLString:[NSString stringWithFormat:@"<html><body style=\"background:transparent;\">%@</body></html>", HTML_]
                   baseURL:nil];
}


- (NSUInteger)height {
  return loaded_ ? [webView_ frame].size.height : 0;
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
  loaded_ = YES;
  [webView_ setHidden:NO];

  CGRect frame = CGRectMake(10, 0, 280, 1);
  [webView_ setFrame:frame];
  [webView_ sizeToFit];

  frame = [webView_ frame];
  frame.size.width = 280.0;
  [webView_ setFrame:frame];

  [delegate_ webTableViewCell:self loadedWithHeight:frame.size.height];
}


- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType {
  if (!loaded_ && navigationType == UIWebViewNavigationTypeOther) {
    return YES;
  } else {
    return [delegate_ webTableViewCell:self
            shouldStartLoadWithRequest:request
                        navigationType:navigationType];
  }
}


- (void)dealloc {
  [webView_ release];
  [HTML_ release];
  [userData_ release];

  [super dealloc];
}


@end
